package com.tuling.dynamicthreadpooldemo.threadpool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
public class DynamicThreadPool {
    private ThreadPoolExecutor executor;

    public DynamicThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        this.executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        //executor.allowCoreThreadTimeOut(true);
    }

    public void adjustThreadPool(int newCorePoolSize, int newMaximumPoolSize) {
        this.executor.setCorePoolSize(newCorePoolSize);
        this.executor.setMaximumPoolSize(newMaximumPoolSize);
    }

    public void submitTask(Runnable task) {
        this.executor.execute(task);
    }

    public void print(){
        System.out.println("核心线程数：" + executor.getCorePoolSize()
                + " " +"最大线程数：" + executor.getMaximumPoolSize()
                +" " + "活跃线程数：" + executor.getActiveCount());
    }

    public void shutdown() {
        this.executor.shutdown();
    }

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(20);
        DynamicThreadPool dynamicThreadPool = new DynamicThreadPool(3, 10, 10, TimeUnit.SECONDS, workQueue);

        // 提交任务给线程池
        for (int i = 0; i < 20; i++) {
            dynamicThreadPool.submitTask(() -> {
                log.info(Thread.currentThread().getName() + "开始执行任务");
                try {
                    Thread.sleep(10000);
                    //log.info(Thread.currentThread().getName() + "任务执行完成");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        Thread.sleep(1000);
        System.out.println("======修改前=======");
        dynamicThreadPool.print();

        // 动态调整线程池参数
        dynamicThreadPool.adjustThreadPool(5, 8);

        System.out.println("======修改后=======");
        dynamicThreadPool.print();


        Thread.sleep(10000);
        dynamicThreadPool.print();

//        // 关闭线程池
//        dynamicThreadPool.shutdown();
    }
}